<?php
namespace Admin\Controller;

use Common\Controller\RequestController;
use ZipArchive;//第三方请求类 BY NYJ

class FindController extends AdminController
{
    //征信员权限（查询）
    protected function _initialize()
    {
        parent::_initialize();
    }

    //首页
    public function index()
    {
        $this->display();
    }

    // 下载照片 主贷人
    public function downloadPic()
    {
        $nUserId  = $_GET['userid'];

        $_tmpUser = M('user')->field('credit_authorize_up,credit_authorize_photo,identity_photo_pros,identity_photo_cons') -> where(['id' => $nUserId])->find();

        $picList  = [];

        // foreach ($_tmpUser as &$_pic)
        // {
        //     if (!is_null($_pic) && !empty($_pic))
        //     {
        //         $_pic = './'.strstr($_pic,'Uploads');
        //     }

        //     array_push($picList, $_pic);
        // }

        $filename = 'Lender'.time().".zip";

        if(!file_exists($filename))
        {
            $zip = new \ZipArchive();
            if ($zip->open($filename, \ZipArchive::CREATE)==TRUE)
            {
                foreach( $_tmpUser as $val)
                {
                    $_filename = basename($val);
                    $curl = curl_init($val);
                    curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
                    $imageData = curl_exec($curl);
                    curl_close($curl);
                    $tp = fopen($_filename,"a");
                    fwrite($tp, $imageData);
                    fclose($tp);

                    if(file_exists($_filename))
                    {
                        $zip->addFile( $_filename, basename($_filename));
                        $picList[] = $_filename;
                    }

                }
                $zip->close();
            }
        }

        if(!file_exists($filename))
        {
            exit("无法找到文件");
        }

        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename='.basename($filename)); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: '. filesize($filename)); //告诉浏览器，文件大小
        @readfile($filename);
        unlink($filename);
        foreach ($picList as $unlink_file)
        {
            unlink($unlink_file);
        }
    }

    // 下载照片 配偶
    public function downloadSpousePic()
    {
        $nUserId  = $_GET['userid'];

        $_tmpUser = M('user')->field('spouse_id_photo_pros,spouse_id_photo_cons,spouse_credit_photo,spouse_credit_up') -> where(['id' => $nUserId])->find();

        $picList  = [];

        $filename = 'Spouse'.time().".zip";

        if(!file_exists($filename))
        {
            $zip = new \ZipArchive();
            if ($zip->open($filename, \ZipArchive::CREATE)==TRUE)
            {
                foreach( $_tmpUser as $val)
                {
                    $_filename = basename($val);
                    $curl = curl_init($val);
                    curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
                    $imageData = curl_exec($curl);
                    curl_close($curl);
                    $tp = fopen($_filename,"a");
                    fwrite($tp, $imageData);
                    fclose($tp);

                    if(file_exists($_filename))
                    {
                        $zip->addFile( $_filename, basename($_filename));
                        $picList[] = $_filename;
                    }
                }
                $zip->close();
            }
        }

        if(!file_exists($filename))
        {
            exit("无法找到文件");
        }

        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename='.basename($filename)); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: '. filesize($filename)); //告诉浏览器，文件大小
        @readfile($filename);
        unlink($filename);
        foreach ($picList as $unlink_file)
        {
            unlink($unlink_file);
        }
    }

    // 下载照片 担保人
    public function downloadAssurePic()
    {
        $nUserId     = $_GET['userid'];

        $_assureList = M('assure')->field('assume_credit_photo,assure_id_photo_pros,assure_id_photo_cons,credit_up_photo')->where(['user_id' => $nUserId])->select();

        $picList     = [];

        $filename    = 'Assure'.time().".zip";

        if(!file_exists($filename))
        {
            $zip = new \ZipArchive();
            if ($zip->open($filename, \ZipArchive::CREATE)==TRUE)
            {
                foreach( $_assureList as $val)
                {
                    $_filename = basename($val);
                    $curl = curl_init($val);
                    curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
                    $imageData = curl_exec($curl);
                    curl_close($curl);
                    $tp = fopen($_filename,"a");
                    fwrite($tp, $imageData);
                    fclose($tp);

                    if(file_exists($_filename))
                    {
                        $zip->addFile( $_filename, basename($_filename));
                        $picList[] = $_filename;
                    }
                }
                $zip->close();
            }
        }

        if(!file_exists($filename))
        {
            exit("无法找到文件");
        }

        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename='.basename($filename)); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: '. filesize($filename)); //告诉浏览器，文件大小
        @readfile($filename);
        unlink($filename);
        foreach ($picList as $unlink_file)
        {
            unlink($unlink_file);
        }
    }

    public function getFile($value='')
    {
        $filename = time().".zip";
        $datalist=array('./Uploads/2017-06-23/594cd67838242.jpg','./Uploads/2017-06-29/5954d080c3288.jpg','./Uploads/2017-06-23/594cd6782518e.png','./Uploads/2017-06-09/593a1a28ddfdc.png');//'./Uploads/2017-06-09/593a1a28ddfdc.png',

        if(!file_exists($filename))
        {
         $zip = new \ZipArchive();
         if ($zip->open($filename, \ZipArchive::CREATE)==TRUE) {
          foreach( $datalist as $val){
           if(file_exists($val)){
            $zip->addFile( $val, basename($val));
           }
          }
          $zip->close();
         }
        }

        if(!file_exists($filename)){
         exit("无法找到文件");
        }

        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename='.basename($filename)); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: '. filesize($filename)); //告诉浏览器，文件大小
        @readfile($filename);
    }

    // 手机时长验证
    public function mobileLength()
    {
        $strPhone      = $_POST['mobile'];

        $str_url       = 'http://tianxingshuke.com/api/rest/common/organization/auth';

        $ret           = RequestController::loadJsonByUrl($str_url,'post',['account' => 'ryzb','signature' => '3bf10c08ba7546a29dfae4dbd1aa3775']);
        $accessToken   = $ret['data']['accessToken'];

        $query         = 'tianxingshuke.com/api/rest/operators/mobile/onlinetime';
        $p_data        = 'account=ryzb&accessToken='.$accessToken.'&mobile='.$strPhone;
        $onlinetime    = RequestController::loadJsonByUrl($query,'get',$p_data);

        $strOnlinetime = '接口无数据返回';
        if ($onlinetime['success'])
        {
            $strOnlinetime = $onlinetime['data']['onlineTime'];
        }
        echo json_encode(['msg' => $strOnlinetime]);exit();
    }

    // 个人信用
    public function queryPersonalCredit()
    {
        $strName   = $_POST['name'];
        $strIdCard = $_POST['idCard'];
        $url = 'http://tianxingshuke.com/api/rest/common/organization/auth';
//        $requestTokenData = array('account' => 'ryzb', 'signature' =>  '3bf10c08ba7546a29dfae4dbd1aa3775');
        $url .= '?account=' . 'ryzb' .'&signature=' .  '3bf10c08ba7546a29dfae4dbd1aa3775';
        $ret    = RequestController::loadJsonByUrl($url,'post');

        $accessToken = $ret['data']['accessToken'];

        $query       = 'test.pintuzhengxin.com/api/rest/riskTip/blackInfo';
        $p_data      = 'account=ryzb&accessToken='.$accessToken.'&name='.$strName.'&idCard='.$strIdCard;
        $blackInfo   = RequestController::loadJsonByUrl($query,'get',$p_data);

        if ($blackInfo['success'])
        {
            switch ($blackInfo['data']['status'])
            {
                case 'SUCCESS':
                    $msgInfo = '该客户经询有逾期记录';
                    break;

                case 'NO_DATA':
                    $msgInfo = ' 无数据';
                    break;

                case 'FAIL':
                    $msgInfo = '查询失败，请重试或者联系管理员';
                    break;

                default:
                    $msgInfo = '接口无数据返回';
                    break;
            }
        }

        echo json_encode(['msg' => $msgInfo]);exit();
    }

    // 配偶
    public function spouseNegativeCheck()
    {
        $nUserId     = $_POST['user_id'];
        $_user       = M('user')->where(['id' => $nUserId])->find();//用户信息
        if ($_user['spouse_negative_info'])
        {
            echo json_encode(['msg' => $_user['spouse_negative_info']]);exit();
        }

        $strNegative_info = $this->queryNegative($_user['spouse_name'],$_user['spouse_identity_no']);

        if (empty($_user['spouse_negative_info']))
        {
            M('user')->where(['id' => $nUserId])->save(['spouse_negative_info' => $strNegative_info,'update_time' => time()]);
        }

        echo json_encode(['msg' => $strNegative_info]);exit();
    }

    // 担保人
    public function assureNegativeCheck()
    {
        $nAssure_id = $_POST['assure_id'];
        $_assure    = M('assure')->where(['id' => $nAssure_id])->find();//用户信息
        if ($_assure['negative_info'])
        {
            echo json_encode(['msg' => $_assure['negative_info']]);exit();
        }

        $strNegative_info = $this->queryNegative($_assure['user_name'],$_assure['identity_no']);

        if (empty($_assure['negative_info']))
        {
            M('assure')->where(['id' => $nAssure_id])->save(['negative_info' => $strNegative_info,'update_time' => time()]);
        }

        echo json_encode(['msg' => $strNegative_info]);exit();
    }

    /**
     * [查询负面信息]
     * @param  [type] $p_name   [姓名]
     * @param  [type] $p_idCard [身份证号]
     * @return [type]           [负面信息描述]
     */
    protected function queryNegative($p_name,$p_idCard)
    {
        $str_url     = 'http://tianxingshuke.com/api/rest/common/organization/auth';

        $str_url .= '?account=' . 'ryzb' .'&signature=' .  '3bf10c08ba7546a29dfae4dbd1aa3775';
        $ret         = RequestController::loadJsonByUrl($str_url,'post');
        $accessToken = $ret['data']['accessToken'];

        $query       = 'tianxingshuke.com/api/rest/police/negativeV2?';
        $p_data      = 'account=ryzb&accessToken='.$accessToken.'&name='.$p_name.'&idCard='.$p_idCard.'&escape=true&crime=true&drug=true&drugRelated=true';

        $negativeV2  = RequestController::loadJsonByUrl($query,'get',$p_data);

        if ($negativeV2['data']['status'] == 'NO_DATA')
        {
            $strNegative_info = '无信息';
        }
        else
        {
            $escapeCompared      = $negativeV2['data']['escapeCompared'];//在逃比对结果
            $crimeCompared       = $negativeV2['data']['crimeCompared'];//前科比对结果
            $drugCompared        = $negativeV2['data']['drugCompared'];//吸毒比对结果
            $drugRelatedCompared = $negativeV2['data']['drugRelatedCompared'];//涉毒比对结果

            if ($escapeCompared == '一致') {
                $strNegative_info = '在逃';
            }else if ($crimeCompared == '一致') {
                // foreach ($negativeV2['data']['caseTime'] as $_timeCase)
                // {
                //     $_timeCase = _timeCase;
                // }
                $strNegative_info = $negativeV2['data']['checkCount'].'次前科,距今'.$negativeV2['data']['caseTime'][0].'年，'.$negativeV2['data']['caseType'];
            }elseif ($drugCompared == '一致') {
                $strNegative_info = '吸毒';
            }else if($drugRelatedCompared == '一致'){
                $strNegative_info = '涉毒';
            }

        }

        return $strNegative_info;
    }

    // 主贷人犯罪记录查询
    public function negativeCheck()
    {
        $nUserId     = $_POST['user_id'];
        $_user       = M('user')->where(['id' => $nUserId])->find();//用户信息
        if ($_user['negative_info'])
        {
            echo json_encode(['msg' => $_user['negative_info']]);exit();
        }

        $strNegative_info = $this->queryNegative($_user['user_name'],$_user['identity_no']);

        if (empty($_user['negative_info']))
        {
            M('user')->where(['id' => $nUserId])->save(['negative_info' => $strNegative_info,'update_time' => time()]);
        }

        echo json_encode(['msg' => $strNegative_info]);exit();
    }

    public function preloanReport()
    {
        $ret = RequestController::pre_loan_report($_POST['report_id']);
        echo json_encode($ret);
    }

    // 同盾查询【配偶】
    public function preloanApply()
    {
        $_user = M('user')->where(['id' => $_POST['user_id']])->find();
        $pr_data["name"]      = $_user['spouse_name'];  // 姓名,必填
        $pr_data["id_number"] = $_user['spouse_identity_no'];  // 身份证号,必填
        $pr_data["mobile"]    = $_user['spouse_telephone'];  // 手机号,必填

        $ret = RequestController::pre_loan_apply($pr_data);

        if ($ret['success'])
        {
            $retTD = RequestController::pre_loan_report($ret['report_id']);
            echo json_encode($retTD);
        }
    }

    // 同盾查询【担保人】
    public function assureTd()
    {
        $_user = M('assure')->where(['id' => $_POST['assure_id']])->find();
        $pr_data["name"]      = $_user['user_name'];  // 姓名,必填
        $pr_data["id_number"] = $_user['identity_no'];  // 身份证号,必填
        $pr_data["mobile"]    = $_user['telephone'];  // 手机号,必填

        $ret = RequestController::pre_loan_apply($pr_data);

        if ($ret['success'])
        {
            $retTD = RequestController::pre_loan_report($ret['report_id']);
            echo json_encode($retTD);
        }
    }

    //央行征信查询
    public function Bank_credit()
    {
        if (IS_POST)
        {
            $user_id = $_POST['user_id'];
            $count = count($_POST['aids']);


            $_tmpUser = $this->getInfo('admin_id,id,user_name', 'user', ['id' => $user_id]);
            for ($i = 0; $i < $count; $i++)
            {
                $aid = $_POST['aids'][$i];
                $data = ['assure_info'=>$_POST['assure_' . $aid],'negative_info'=>$_POST['assure_negative_'.$aid]];
                $this->updateData($data, 'assure', 2, 'user_id =' . $user_id . ' and id=' . $aid);
            }
            //判空不需要信息剔除
//            $t = array_keys(array_map('trim', $_POST), '');//如果空格算空，就用这条
//            if (!empty($t))
//            {
//                foreach ($t as $_nullField) {
//                    unset($_POST[$_nullField]);
//                }
//            }

            $nCheck_status = $_POST['check_status'];
            switch ($nCheck_status)
            {
                case -1://审核通过
                    $_POST['status'] = 1;
                    $_POST['check_status'] = -1;

                    $strTitle = '您提交的客户【' . $_tmpUser['user_name'] . '】征信结果查询完毕\n' . date('Y-m-d h:i:s');
                    $strDescription = '您查询客户' . $_tmpUser['user_name'] . '的征信结果如下：购车人' . $_POST['master_info'].'负面信息结果：'.$_POST['negative_info'];

                    if (!empty($_POST['spouse_info'])) {
                        $strDescription .=  '；共同购车人：' . $_POST['spouse_info'].'配偶负面信息结果'.$_POST['spouse_negative_info'];
                    }

                    for ($i = 0; $i < $count; $i++) {
                        $aid = $_POST['aids'][$i];
                        $strDescription .=  '；担保人' . $i . ':' .$_POST['assure_' . $aid].'担保负面'.$i.'信息结果:'.$_POST['assure_negative_'.$aid];
                    }

                    $status_local = '征信结果查询完毕';

                    // 央行征信通过日志
                    $log = array('user_id' => $user_id, 'admin_id' => session('adminInfo.id'), 'admin_name' => session('adminInfo.name'), 'type' => session('adminInfo.group_name'), 'check_status' => -4, 'opinion' => '央行征信查询通过', 'note' =>$strDescription , 'add_time' => time());

                    M('check_log')->add($log);

                    break;

                case 901://审核驳回
                    $_POST['status'] = 9;
                    $_POST['check_status'] = -5;

                    $strTitle = '您提交的客户【' . $_tmpUser['user_name'] . '】征信被驳回' . date('Y-m-d h:i:s');
                    $strDescription = '您查询客户【' . $_tmpUser['user_name'] . '】的征信被驳回' . $_POST['master_info'];

                    $status_local = '征信被驳回';
                    // 央行征信通过日志
                    $log = array('user_id' => $user_id, 'admin_id' => session('adminInfo.id'), 'admin_name' => session('adminInfo.name'), 'type' => session('adminInfo.group_name'), 'check_status' => -5, 'opinion' => '央行征信查询驳回', 'note' =>$strDescription , 'add_time' => time());

                    $result=M('check_log')->add($log);

                    break;
            }

            // 消息添加
            $msg = M('message')->
            data(['status_local' => $status_local, 'admin_id' => $_tmpUser['admin_id'], 'operator_id' => session('adminInfo.id'), 'user_id' => $user_id, 'title' => $strTitle, 'description' => $strDescription, 'create_time' => time()])->
            add();

            $ret = $this->updateData($_POST, 'user', 2, 'id = ' . $user_id);

            $this->redirect('Find/credit_list');
        }

        $nUserId    = $_GET["user_id"];
        $info       = $this->getInfo('u.*,ad.name as admin_name', 'user as u', 'u.id=' . $nUserId, 'app_admins as ad on u.admin_id = ad.id');
        $assure     = $this->getList('*', 'assure', 'user_id=' . $nUserId, '');
        $contactors = $this->getList('*', 'emergency_contact', 'user_id = ' . $nUserId, ' id desc ');

        if (empty($info)) {
            $this->error('该ID为：' . $_GET['user_id'] . '获取信息失败');
        }

        $tmp_bank = $this->getInfo('bank_name', 'bank', 'id = ' . $info['loan_bank_id']);
        $info['bank_name'] = $tmp_bank['bank_name'];
        $this->assign('info', $info);
        $this->assign('assure', $assure);
        $this->assign('contactors', $contactors);
        $this->display();
    }

    //提交列表
    public function credit_list()
    {
        $where = '1 = 1';
        if (I('get.aid', -1, 'intval') <> -1) {
            if (I('get.aid', -1, 'intval') == 0) {
                $where .= ' and  u.aid =0';
            } else {
                $where .= ' and u.aid=' . I('get.aid', 0, 'intval');
            }
        }
        $where .= I('get.user_name') != '' ? ' and u.user_name like "%' . I('get.user_name') . '%"' : '';

        $where .= I('get.telephone') != '' ? ' and u.telephone = ' . I('get.telephone') : '';

        $where .= I('get.create_time_beg') != '' ? ' and u.create_time >= ' . strtotime(I('get.create_time_beg')) : '';

        $where .= I('get.create_time_end') != '' ? ' and u.create_time < ' . strtotime(I('get.create_time_end')) : '';

        // $nStatus = I('get.status');
        // if (!empty($nStatus)) {
        //     $where .= $nStatus > -1 && !is_null($_GET['status']) ? ' and u.status=' . $nStatus : '';
        // }

        $where .= ' and u.status != 0';

        // $nCheck_Status = I('get.check_status');
        // if (!empty($nCheck_Status)) {
        //     $where .= $nCheck_Status > -1 && !is_null($_GET['check_status']) ? ' and u.check_status=' . $nCheck_Status : '';
        // }

        $where .= ' and u.check_status = -4';

        $nPage     = isset($_GET['p'])? intval($_GET['p']) : 1;
        $userModel = M('user u');
        $pagesize  = 15;#每页数量
        $offset    = $pagesize * ($nPage - 1);//计算记录偏移量
        $order     = isset($_GET['order']) ? $_GET['order'] : 'DESC';

        $count     = $userModel->where($where)->count();

        $list  = $userModel->field('u.status,u.id,u.entry_no,u.create_time,u.user_name,u.telephone,u.department_name,u.dealer_name,u.identity_no,b.bank_short_name')
            ->join('app_bank b on u.loan_bank_id = b.id')
            ->where($where)
            ->order('u.id desc')
            ->limit($offset . ',' . $pagesize)
            ->select();

        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->display();
    }

    /**
     * [getAllUsers 根据条件获取制定筛选的用户列表]
     * @return [type] [Array]
     * @param  [status 0: 正常 1: 草稿 2: 待审 3：删除  4央行征信通过 5拒绝贷款 6公检法审核通过 [含同盾] 9:审核不通过  901央行征信不通过 902 公检法审核不通过]
     * @author [NYJ]
     */
    protected function getAllUsers($p_status = null, $p_check_status = null)
    {
        $where = '1 = 1';
        if (I('get.aid', -1, 'intval') <> -1) {
            if (I('get.aid', -1, 'intval') == 0) {
                $where .= ' and  u.aid =0';
            } else {
                $where .= ' and u.aid=' . I('get.aid', 0, 'intval');
            }
        }
        $where .= I('get.user_name') != '' ? ' and u.user_name like "%' . I('get.user_name') . '%"' : '';

        $where .= I('get.telephone') != '' ? ' and u.telephone = ' . I('get.telephone') : '';

        $where .= I('get.create_time_beg') != '' ? ' and u.create_time >= ' . strtotime(I('get.create_time_beg')) : '';

        $where .= I('get.create_time_end') != '' ? ' and u.create_time < ' . strtotime(I('get.create_time_end')) : '';

        $nStatus = I('get.status');
        if (!empty($nStatus)) {
            $where .= $nStatus > -1 && !is_null($_GET['status']) ? ' and u.status=' . $nStatus : '';
        } else if (!is_null($p_status)) {
            $where .= ' and u.status ' . $p_status;
        }
        $nCheck_Status = I('get.check_status');
        if (!empty($nCheck_Status)) {
            $where .= $nCheck_Status > -1 && !is_null($_GET['check_status']) ? ' and u.check_status=' . $nCheck_Status : '';
        } else if (!is_null($p_check_status)) {
            $where .= ' and u.check_status ' . $p_check_status;
        }

        $list = $this->getList('u.status,u.id,u.entry_no,u.create_time,u.user_name,u.telephone,u.department_name,u.dealer_name,u.identity_no,b.bank_short_name', 'user u join app_bank b on u.loan_bank_id=b.id ', $where, 'id desc', true);
        return $list;
    }

    //检察院法院查询
    public function Procuracy()
    {
        $list = $this->getAllUsers('!=0', '=-3');
        $this->assign('list', $list);
        $this->display();
    }

    public function access_gjf()
    {
        if (IS_POST) {
            $user_id = $_POST['user_id'];
            $_tmpUser = $this->getInfo('admin_id,id,user_name', 'user', ['id' => $user_id]);
            //判空不需要信息剔除
            $t = array_keys(array_map('trim', $_POST), '');//如果空格算空，就用这条

            if (!empty($t)) {
                foreach ($t as $_nullField) {
                    unset($_POST[$_nullField]);
                }
            }

            $nCheck_status = $_POST['check_status'];

            switch ($nCheck_status) {
                case -2://审核通过
                    $_POST['status'] = 1;
                    $_POST['check_status'] = -2;

                    $strTitle = '您提交的客户【' . $_tmpUser['user_name'] . '】公检法查询完毕 \n' . date('Y-m-d h:i:s');
                    $strDescription = '您查询的客户' . $_tmpUser['user_name'] . '公检法结果：同意';
                    $status_local = '公检法结果：同意';
                    break;

                case 902://审核驳回
                    $_POST['status'] = 12;
                    $_POST['check_status'] = -5;

                    $strTitle = '您提交的客户【' . $_tmpUser['user_name'] . '】公检法驳回 ' . date('Y-m-d h:i:s');
                    $strDescription = '您查询客户【' . $_tmpUser['user_name'] . '】的公检法驳回';
                    $status_local = '公检法审核不通过';
                    break;
            }

            // 消息添加
            $msg = M('message')->
            data(['status_local' => $status_local, 'admin_id' => $_tmpUser['admin_id'], 'operator_id' => session('adminInfo.id'), 'user_id' => $user_id, 'title' => $strTitle, 'description' => $strDescription, 'create_time' => time()])->
            add();

            $ret = $this->updateData($_POST, 'user', 2, 'id = ' . $user_id);

            // 公检法通过日志
            $log = array('user_id' => $user_id, 'admin_id' => session('adminInfo.id'), 'admin_name' => session('adminInfo.name'), 'type' => session('adminInfo.group_name'), 'check_status' => -3, 'opinion' => '公检法查询通过', 'note' => '公检法查询通过', 'add_time' => time());

            M('check_log')->add($log);

            $this->redirect('Find/Procuracy');
        }

        $nUserId = $_GET["user_id"];
        $info = $this->getInfo('u.*,ad.name as admin_name', 'user as u', 'u.id=' . $nUserId, 'app_admins as ad on u.admin_id = ad.id');

        if (empty($info)) {
            $this->error('该ID为：' . $_GET['user_id'] . '获取信息失败');
        }
        $assure = $this->getList('*', 'assure', 'user_id=' . $nUserId, '');
        $tmp_bank = $this->getInfo('bank_name', 'bank', 'id = ' . $info['loan_bank_id']);
        $info['bank_name'] = $tmp_bank['bank_name'];
        $this->assign('info', $info);
        $this->assign('assure', $assure);
        $this->display();
    }

    public function credit_check()
    {
        $p_url = 'http://happyleasing.cn/TMZL/app/lywxapi.htm!?.url=autoFinancingPreApplyt';

        if (IS_POST)
        {
            $data = ['param' => json_encode($_POST)];
            $re = RequestController::loadStringByUrl($p_url, 'post', $data);
            echo $re;
            exit();
        }
    }

    public function check_result()
    {
        $p_url_checkResult = 'http://happyleasing.cn/TMZL/app/lywxapi.htm!?.url=qureyFinancePreApplyResultt';//测试提交
        if (IS_POST)
        {
            $data = ['param' => json_encode([$_POST['applyId']])];

            $re = RequestController::loadStringByUrl($p_url_checkResult, 'post', $data);
            echo $re;
            exit();
        }
    }

    //互金平台查询
    public function Money()
    {
        $this->display();
    }

    //第三方征信查询
    public function tongdun()
    {
        $list = $this->getAllUsers('!=0', '=-2');
        $this->assign('list', $list);
        $this->display();
    }

    public function Third()
    {
        if (IS_POST)
        {
            // 操作逻辑写在 if里面
            $user_id = $_POST['user_id'];
            //判空不需要信息剔除
            $t = array_keys(array_map('trim', $_POST), '');//如果空格算空，就用这条

            if (!empty($t))
            {
                foreach ($t as $_nullField) {
                    unset($_POST[$_nullField]);
                }
            }

            $_tmpUser = $this->getInfo('admin_id,id,user_name', 'user', ['id' => $user_id]);

            $nCheck_status = $_POST['check_status'];

            if ($nCheck_status == -1)
            {
                $_POST['status'] = 1;
                $_POST['check_status'] = -1;

                $strTitle = '您提交的客户【' . $_tmpUser['user_name'] . '】同盾查询完毕 ' . date('Y-m-d h:i:s');
                $strDescription = '您查询客户【' . $_tmpUser['user_name'] . '】的同盾结果：同意；同盾分数：' . $_POST['score'];
                $status_local = '同盾查询通过';

                // 消息添加
                $msg = M('message')->
                data(['status_local' => $status_local, 'admin_id' => $_tmpUser['admin_id'], 'operator_id' => session('adminInfo.id'), 'user_id' => $user_id, 'title' => $strTitle, 'description' => $strDescription, 'create_time' => time()])->
                add();
            }

            $ret = $this->updateData($_POST, 'user', 2, 'id = ' . $user_id);

            // 同盾通过日志
            $log = array('user_id' => $user_id, 'admin_id' => session('adminInfo.id'), 'admin_name' => session('adminInfo.name'), 'type' => session('adminInfo.group_name'), 'check_status' => -2, 'opinion' => '同盾查询通过，同盾分数为：' . $_POST['score'], 'note' => '同盾查询通过', 'add_time' => time());

            M('check_log')->add($log);

            $this->redirect('Find/tongdun');//跳转路径
        }

        $nUserId = $_GET["user_id"];
        $info    = $this->getInfo('u.*,ad.name as admin_name', 'user as u', 'u.id=' . $nUserId, 'app_admins as ad on u.admin_id = ad.id');

        if (empty($info))
        {
            $this->error('该ID为：' . $_GET['user_id'] . '获取信息失败');
        }
        $assure            = $this->getList('*', 'assure', 'user_id=' . $nUserId, '');
        $tmp_bank          = $this->getInfo('bank_name', 'bank', 'id = ' . $info['loan_bank_id']);
        $info['bank_name'] = $tmp_bank['bank_name'];
        $this->assign('info', $info);
        $this->assign('assure', $assure);
        $this->display();
    }

    //征信照片导出另存为word
    public function creditPhotoDown()
    {
//        header('Content-Type:text/html; charset=utf8');
        require_cache(VENDOR_PATH . 'PHPWord.php');
        $PHPWord = new \PHPWord();//新建一个
        $user_type = $_GET['user_type'];

        if ($user_type == 1)
        {
            $nUserId = $_GET['nUserId'];
            $info = $this->getInfo('*', 'user', 'id=' . $nUserId);
            $image = array(
                "." . substr($info['identity_photo_pros'], 21),//将路径优化为本地路径
                "." . substr($info['identity_photo_cons'], 21),
                "." . substr($info['credit_authorize_photo'], 21),
                "." . substr($info['credit_authorize_up'], 21),
            );
            $fileName = $info['user_name'];
        }

        if ($user_type == 2)
        {
            $nUserId = $_GET['nUserId'];
            $info = $this->getInfo('*', 'user', 'id=' . $nUserId);
            $image = array(
                "." . substr($info['spouse_id_photo_pros'], 21),
                "." . substr($info['spouse_id_photo_cons'], 21),
                "." . substr($info['spouse_credit_photo'], 21),
                "." . substr($info['spouse_credit_up'], 21),
            );
            $fileName = $info['spouse_name'];
        }

        if ($user_type == 3)
        {
            $nUserId = $_GET['assureId'];
            $info = $this->getInfo('*', 'assure', 'id=' . $nUserId);
            $image = array(
                "." . substr($info['assure_id_photo_pros'], 21),
                "." . substr($info['assure_id_photo_cons'], 21),
                "." . substr($info['assume_credit_photo'], 21),
                "." . substr($info['credit_up_photo'], 21),
            );
            $fileName = $info['user_name'];
        }

        $section = $PHPWord->createSection();
        foreach ($image as $images)
        {
            $section->addImage($images, array('width' => '600px', 'height' => '800px', 'align' => 'center'));//添加一个图片文件
        }

        header("Content-type: application/vnd.ms-word");
        header("Content-Disposition:attachment;filename=" . $fileName . ".doc");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');//保存为word格式文件，
        $objWriter->save('php://output');
    }
}